import Qfpage from "../../components/Qfpage/Qfpage";
import { 
    PrimaryTable,
    Button,
    Drawer, 
    Form, 
    Input ,
    InputNumber,
    MessagePlugin,
    DialogPlugin,
    Row,
    Col,
    InputAdornment,
    Radio,
    Cascader,
    Select,
    Tag
} from 'tdesign-react'

import { useMemo ,useEffect,useState, useRef,useLayoutEffect} from "react";
import { getAllRoom,delRoom,addRoom, editRoom  }  from '../../api/room'
import { getAllBuild } from "../../api/build";
import { getAllType } from "../../api/roomType";
const RoomList = ()=>{


    // 获取全部的楼栋信息
    const [ build,setBuild] = useState([])
    const getBuild = async ()=>{
        let res = await getAllBuild({});
        console.log('res',res)
        // 实际开发过程当中 得到的数据格式不一定符合我们的要求
        // 我们需要处理成我们要用的数据格式
        const temarr = res.data.map(item=>({
            label:item.name,
            value:item._id,
            children: item.floorInfo.map(it=>({ label:it,value:it }))
        }))
        setBuild(temarr)
    }
    useEffect(()=>{
        getBuild();  // 获取楼栋信息
    },[])
    

    // 获取全部的房型

    const [type,setType] = useState([]);
    const getTypes =  async ()=>{
        const res = await getAllType({limit:2000});
        setType(res.data.map(item=>({ label: item.name, value:item._id})))
    }
    useEffect(()=>{
        getTypes();  // 获取全部的房型信息
    },[])
    




    const [data,setData] = useState([]);
    const [limit,setLimit] = useState(30);  // 单页数量
    const [page,setPage] = useState(1); 
    const [total ,setTotal] = useState(0); // 总数
   // 获取表格数据的主函数
    const getData = async ()=>{
        const postData = { limit,page };
        if(name) postData.name = name;
        if(price) postData.price = price;

        let res = await getAllRoom(postData)
        const {  success ,data, count} = res;
        if(success) {
            setData(data);
            setTotal(count)
        };   
    }
 
    // 条件过滤
    const [name,setName] = useState('');
    const [price,setPrice] =useState('')
    

    useLayoutEffect(()=>{
        getData(); // 获取表格数据
      
    },[limit,page])


    const confirmDel = async (id)=>{
        let res = await delRoom({roomid: id});
        const  {success} = res;
        if(!success) return  MessagePlugin.warning('删除失败')
        MessagePlugin.success('删除成功');
        getData();
    }

    const handlerDel =  (id)=>{
        const delDialog = DialogPlugin({
            header: '提醒',
            body: '你确定要删除当前的房型吗？',
            onConfirm: ()=>{
                delDialog.hide();
                confirmDel(id); // 执行删除
            } , 
            onClose: ({ e, trigger }) => {
                delDialog.hide()
            },
        });
    }

    // 表格列的定义
    const columns = useMemo(()=>[
            {   title:'房间名称', colKey:'roomName' },
            {   title:'楼层', colKey:'floor'   },
            {  title:'是否有窗', colKey: 'hasWindow', cell({row}){
                const { hasWindow } = row
                const theme =  hasWindow ? 'success':'danger'
                const txt =  hasWindow ? '有':'无'
                return <Tag theme={theme} variant="light"> { txt } </Tag>
            }},
            {  title:'靠近马路', colKey: 'isClose2Road', cell({row}){
                const { isClose2Road } = row
                const theme =  isClose2Road ? 'success':'danger'
                const txt =  isClose2Road ? '是':'否'
                return <Tag theme={theme} variant="light"> { txt } </Tag>
            }},
            {  title:'允许吸引', colKey: 'isSmoke', cell({row}){
                const { isSmoke } = row
                const theme =  isSmoke ? 'success':'danger'
                const txt =  isSmoke ? '是':'否'
                return <Tag theme={theme} variant="light"> { txt } </Tag>
            }},
            {  title:'高温房', colKey: 'isHigh', cell({row}){
                const { isHigh } = row
                const theme =  isHigh ? 'success':'danger'
                const txt =  isHigh ? '是':'否'
                return <Tag theme={theme} variant="light"> { txt } </Tag>
            }},

            {   title:'操作', colKey:'colKey',
                cell:({row})=>{  // 这一列的是通过cell的方法来返回的值进行渲染的
                
                    return <> 
                                <Button  variant="outline" size="small" onClick={()=>handlerDel(row._id)}>删除</Button> 
                                <Button variant="outline"  style={{marginLeft:'5px'}} size="small" onClick={()=>openEdit(row)}>修改</Button> 
                         </>
                }
            }
    ],[])


    const formRef = useRef(null)


    // 添加房型的操作
    
    const rules = {// 表单的校验规则
        roomName: [ { required:true,message:'不可能不填吧',type:'error' }],
        bandf: [ { required:true,message:'不可能不填吧',type:'error' }],
        type: [ { required:true,message:'不可能不填吧',type:'error' }],
        direction: [ { required:true,message:'不可能不填吧',type:'error' }],
        isClose2Road: [ { required:true,message:'不可能不填吧',type:'error' }],
        isSmoke: [ { required:true,message:'不可能不填吧',type:'error' }],
        isNoise: [ { required:true,message:'不可能不填吧',type:'error' }],
        isHigh: [ { required:true,message:'不可能不填吧',type:'error' }],


    } 
            
    
    const [showAdd,setShowAdd] = useState(false)
    const handleAdd   = async ()=>{
        const okornot = await formRef.current.validate() // 表单验证 通过的话返回true
        if(okornot !== true) return ;
        const values = formRef.current.getFieldsValue(true); // 得到所有的表单的值
        const { bandf , ...postData} = values;
        const [ buildId, floor ] = bandf;
        let res = await addRoom({
            ...postData,
            floor,
            buildId
        });
        const { success } = res;
        if(!success) return MessagePlugin.warning('添加失败');
        MessagePlugin.success('添加成功');
        getData(); // 刷新表格
        formRef.current.reset(); // 重置表单
        setShowAdd(false) // 抽屉隐藏
    }



    // 修改房型的操作

    const [showEdit,setShowEdit] = useState(false);
    const editRef = useRef(null);
    const [curRow,setCurRow] = useState(null)
    const openEdit = (row)=>{
        console.log('row',row)
        setCurRow(row)
        // 设置 修改表单的内容
        editRef.current.setFieldsValue({
            ...row,
            bandf:[row.buildId,row.floor]
        })
        setShowEdit(true); //  让修改抽屉弹出
    }
    const handleEdit   = async ()=>{
        const okornot = await editRef.current.validate() // 表单验证 通过的话返回true
        if(okornot !== true) return ;
        const values = editRef.current.getFieldsValue(true); // 得到所有的表单的值
        const { bandf,...postData } = values;
        const [buildId,floor] = bandf;
        // 发送请求执行修改
        let res = await editRoom({
            ...postData,
            roomid:curRow._id,
            buildId, 
            floor
        });
        const { success } = res;
        if(!success) return MessagePlugin.warning('修改失败');
        MessagePlugin.success('修改成功');
        getData(); // 刷新表格
        setShowEdit(false) // 抽屉隐藏
    }




    return (
        <Qfpage title="房间管理">
           
         <div style={{padding:'15px'}}> 

          <Row>
            <Col span={3}>
                 {/* 操作区域 */}
                 <Button onClick={()=> setShowAdd(true) }>添加房间</Button>
            </Col>
            <Col span={1}></Col>
            <Col span={6}>
                {/* <Input.Group>
                    <Input placeholder="输入你有查询的房型" onChange={setName}  /> 
                    <Input placeholder="按价格查询" onChange={setPrice} />
                </Input.Group> */}
            </Col>
            <Col span={2}>
                {/* <Button onClick={getData}>立即查询</Button> */}
            </Col>
          </Row>
         
          
          
         </div>
           <PrimaryTable  
                columns={columns} 
                data={data} 
                pagination={{
                    defaultPageSize: limit,
                    total,
                    onChange({pageSize,current}){
                       setPage(current);
                       setLimit(pageSize)
                 
                    }
                  }}
            /> 

           {/* 添加房型的 抽屉 */}
           <Drawer 
                visible={showAdd} 
                size="600px" 
                onClose={()=> setShowAdd(false) } 
                confirmBtn="立即添加"
                onConfirm={handleAdd}
            >
                 <Form ref={formRef} rules={rules}> 
                    <Form.FormItem label="房间名" name="roomName">
                        <Input  placeholder="请填写房间名" />
                    </Form.FormItem>
                    <Form.FormItem label="所在楼栋楼层" name="bandf">
                       <Cascader valueType="full" options={build}></Cascader>
                    </Form.FormItem>
                    <Form.FormItem label="选择房型" name="type">
                       <Select options={type}></Select>
                    </Form.FormItem>
                    <Form.FormItem label="内线电话" name="phone4in">
                        <Input  placeholder="请填写内线电话" />
                    </Form.FormItem>
                    <Form.FormItem label="外线电话" name="phone4out">
                        <Input  placeholder="请填写内线电话" />
                    </Form.FormItem>
                    <Form.FormItem label="方向朝向" name="direction">
                        <Radio.Group defaultValue="1">
                                <Radio.Button value="1">东</Radio.Button>
                                <Radio.Button value="2">西</Radio.Button>
                                <Radio.Button value="3">南</Radio.Button>
                                <Radio.Button value="4">北</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否有窗户" name="hasWindow">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否靠近马路" name="isClose2Road">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否允许吸烟" name="isSmoke">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否是噪音房" name="isNoise">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    
                    <Form.FormItem label="是否是高温房" name="isHigh">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                
                 </Form>
           </Drawer>


           {/* 修改房型的抽屉 */}
           <Drawer 
                visible={showEdit} 
                size="600px" 
                onClose={()=> setShowEdit(false) } 
                confirmBtn="立即修改"
                onConfirm={handleEdit}
            >
                <Form ref={editRef} rules={rules}> 
                    <Form.FormItem label="房间名" name="roomName">
                        <Input  placeholder="请填写房间名" />
                    </Form.FormItem>
                    <Form.FormItem label="所在楼栋楼层" name="bandf">
                       <Cascader valueType="full" options={build}></Cascader>
                    </Form.FormItem>
                    <Form.FormItem label="选择房型" name="type">
                       <Select options={type}></Select>
                    </Form.FormItem>
                    <Form.FormItem label="内线电话" name="phone4in">
                        <Input  placeholder="请填写内线电话" />
                    </Form.FormItem>
                    <Form.FormItem label="外线电话" name="phone4out">
                        <Input  placeholder="请填写内线电话" />
                    </Form.FormItem>
                    <Form.FormItem label="方向朝向" name="direction">
                        <Radio.Group defaultValue="1">
                                <Radio.Button value="1">东</Radio.Button>
                                <Radio.Button value="2">西</Radio.Button>
                                <Radio.Button value="3">南</Radio.Button>
                                <Radio.Button value="4">北</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否有窗户" name="hasWindow">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否靠近马路" name="isClose2Road">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否允许吸烟" name="isSmoke">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    <Form.FormItem label="是否是噪音房" name="isNoise">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                    
                    <Form.FormItem label="是否是高温房" name="isHigh">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.FormItem>
                
                 </Form>
           </Drawer>
        </Qfpage>
      
    )
}

export default RoomList;